<?php
	/***
	 * 整体采集：用于整站循环
	 * 作者：elseksy
	 * 仅供测试使用，请勿用于商业用途 
	 */

	include_once('../sys/sys.php');
	include_once ('./data/lndt.php');
	header('Content-Type: text/html; charset=utf-8');
	$action = $_GET['action'];
	if($action != 'acr'){
		show_normal_mesR('操作错误','操作错误','操作错误');
	}
	//获取所有TID并挨个更新
	$nids = $DB->build_and_exec_query(
			array('select' => 'id','from'   => 'lnnovels')
	);
	$DB->build_query(array(
			'select' 	=> 'id',
			'from'		=> 'lnnovels',
	));
	$nqid = $DB->exec_query();
	while ($nrow = $DB->fetch_row($nqid)) {
		$tid = $nrow['id'];
		$id = $tid;
		//取数据库中的小说信息，用于比较
		$where = 'AND id= ' . $tid .'';
		$dbnov_infos = $DB->build_and_exec_query(
				array('select' => '*','from'   => 'lnnovels','where'	=> "1 " . $where ,)
		);
		if(count($dbnov_infos) < 3){
			$dbnov_infos = array();
		}
		//从TID获取总本数以及每本对应连接和更新时间
		$indexurl = make_book_url($ln_base_link,$tid,$ln_n_middle);
		$context = file_get_contents($indexurl);
		//失败重试
		while ($context == false) {
			echo "<font color='red'>读取失败，正在重试</font><BR>";
			ob_flush();
			$context = file_get_contents($indexurl);
		}
		//获取作者
		$author = explode('<td width="120">',$context);
		$author = explode('</td>',$author[1]);
		$author = $author[0];
		//获取最后更新时间(用于第一次检测更新)
		$lastupdate = explode('更&nbsp;&nbsp;新：',$context);
		$lastupdate = explode('						</td>',$lastupdate[1]);
		$lastupdate = explode('							',$lastupdate[0]);
		$lastupdate = $lastupdate[1];
		$lastupdate = strtotime($lastupdate);
		//---------------------------第一次更新比对，如果更新时间相同，则跳过-----------------
		if ($dbnov_infos['lastupdate'] >= $lastupdate){
			//如果时间相同或数据库时间超前，则不需要更新
			echo "<FONT color='red'>本小说" .$dbnov_infos['name'] . "已为最新，无需更新</FONT><br>";
			continue;
		}
		echo "<FONT color='gray'>正在更新小说：==" .$dbnov_infos['name'] . "==</FONT><br>";
		//--------------------------------------------------------------------------------------
		//更新小说信息
		$where = 'AND id= ' . $tid .'';
		$result = $DB->build_and_exec_query(
				array('select' => 'author','from'   => 'lnnovels','where'	=> "1 " . $where ,)
		);
		$dbauthor = $result['author'];
		if ($dbauthor != $author){
			//更新作者信息
			$where = 'id= ' . $tid .'';
			$DB->do_update('lnnovels',array('author' => $author,),	$where);
		}
		//--------------------------------------------------------------------------------------
		//获取总本数
		$ncount = count(explode('<div class="chapter-info well">', $context)) - 1;
		//获取每本的对应信息
		$nov_links = explode('<div class="chapter-info well">', $context);
		$nov_infos = array();
		unset($nov_links[0]);
		foreach ($nov_links as $k=>$v) {
			$kk = $k-1;
			//获取每本连接
			$vol_link = explode('<div class="desc fn-left">', $v);
			$vol_link = explode('<a target="_blank" href="', $vol_link[0]);
			$vol_link = explode('" class="ui-block-cover fn-book', $vol_link[1]);
			$nov_infos['vol_link'][$kk] = $vol_link[0];
			//获取每本名称
			$vol_name = explode('&nbsp;', $v);
			$vol_name = explode('							</a>', $vol_name[1]);
			$nov_infos['vol_name'][$kk] = trim($vol_name[0]);
			//获取每本总章节数
			$li_context = explode('<ul id="chapter" class="unstyled">', $v);
			$li_context = explode('</div>', $li_context[1]);
			$nov_infos['ncount'][$kk] = count(explode('</li>', $li_context[0])) - 1;
			//获取每本ID
			$vol_id = explode('/book/', $vol_link[0]);
			$vol_id = explode('.html', $vol_id[1]);
			$nov_infos['id'][$kk] = $vol_id[0];
			//插入该本信息
			$where = 'AND id= ' . $vol_id[0] .'';
			//不存在则插入
			if(get_scount($where) < 1){
				do_sinsert($nov_infos['id'][$kk], $tid, addslashes($nov_infos['vol_name'][$kk]),0);
				echo "<font color='green'>第" . $k . "本==" . $nov_infos['vol_name'][$kk] . "==正在创建</font><BR>";
				ob_flush();
			}
			//检查整本小说更新
			//首先检查每个小节是否存在（由于存在不按顺序更新的情况，使用inarray方法进行判定）
			//取出该本对应章节在数据库中的ID数组
			$where = 'AND sid= ' . $vol_id[0] .' AND nid= ' . $tid . '';
			$dbsids = $DB->build_and_exec_query(
					array('select' => 'id','from'   => 'lnchapters','where'	=> "1 " . $where ,)
			);
			if ($dbsids == ''){
				$dbsids = array();
			};
			// 		print_r($dbsids);exit;
			//分离该本当前ID数组
			$csids = '';
			$match_str = "/href=\"http:\/\/lknovel.lightnovel.cn\/main\/view\/(.*).html\">/isU";
			preg_match_all($match_str,$li_context[0],$csids);
			//与数据库中的比对
			foreach ($csids[1] as $ck=>$cv) {
				//如果不在数据库中，插入该小节
				if (!in_array($cv, $dbsids)){
					// 				echo "<font color='green'>第" . $k . "本==" . $nov_infos['vol_name'][$kk] . "==正在添加新增小节内容</font><BR>";
					// 				ob_flush();
					do_chapter_insert($cv,$tid,$nov_infos['id'][$kk]);
				}
			}
			//小节插入完毕后更新当前这本书的所有信息
			$where = ' id= ' . $vol_id[0] .'';
			$DB->do_update('lnstories',
					array(
							'count'					=> $nov_infos['ncount'][$kk],
					),
					$where
			);
			echo "<font color='green'>第" . $k . "本==" . $nov_infos['vol_name'][$kk] . "==更新完毕</font><BR>";
			ob_flush();
		}
		//更新小说更新时间以及总本数
		$where = 'id= ' . $tid .'';
		$DB->do_update('lnnovels',array('count' => $ncount,'lastupdate' => $lastupdate,),	$where);
		echo "<font color='gray'>全书更新完毕</font><BR>";
	}
	echo "<font color='gray'>全站更新完毕</font><BR>";
	
	
	
	//-----------------------------------------通用函数定义区
	//章节插入
	function do_chapter_insert($cid,$nid,$sid,$ln_base_link = 'http://lknovel.lightnovel.cn/main/' , $ln_c_middle = "view/"){
		$text = '';
		$curl = make_chapter_url($ln_base_link,$cid,$ln_c_middle);
		$ch_context = file_get_contents($curl);
		//失败重试
		while ($ch_context == false){
			echo "<font color='red'>读取失败，正在重试</font><BR>";
			ob_flush();
			$ch_context = file_get_contents($curl);
		}
		$text = explode('<h3 align="center">', $ch_context);
		//提取该章标题
		$cname = explode('</h3>', $text[1]);
		$cname = $cname[0];
		$text = explode('<br /></div>', $text[1]);
		$text = $text[0] . '<br />';
		$ctext = '';
		//提取所有文本(注意排除图片连接)
		$match_str = "/class=\"ui-line\">([^<]*)<br/isU";
		preg_match_all($match_str,$text,$text);
		//组合内容
		foreach ($text[1] as $v) {
			$ctext .= $v . "\r\n";
		}
		//插入
		//检查是否存在（虽然应该是不存在的）
		$where = 'AND id= ' . $cid .'';
		//不存在则插入
		if(get_ccount($where) < 1){
			do_cinsert($cid, $nid, $sid, $curl, $cname, $ctext);
			echo "<font color='blue'>小节：==" . $cname . "==添加完毕</font><BR>";
			ob_flush();
		}
	}
	//获取当前ID的书是否存在
	function get_scount($where){
		global $DB;
		$result = $DB->build_and_exec_query(
				array('select' => 'count(*) AS count','from'   => 'lnstories','where'	=> "1 " . $where ,)
		);
		return $result['count'];
	}
	//获取当前ID章是否存在
	function get_ccount($where){
		global $DB;
		$result = $DB->build_and_exec_query(
				array('select' => 'count(*) AS count','from'   => 'lnchapters','where'	=> "1 " . $where ,)
		);
		return $result['count'];
	}
	//插书
	function do_sinsert($id,$nid,$name,$count = 0){
		global $DB;
		$result = $DB->do_insert( 'lnstories', array(
				'id'				=> $id,
				'nid'				=> $nid,
				'name'				=> $name,
				'count'				=> $count,
		)		);
		if ($result === false) {
			show_normal_mesR('无法添加当前小说当前本','添加出错','添加');
		}
	}
	//插小节
	function do_cinsert($id,$nid,$sid,$url,$name,$text){
		global $DB;
		$result = $DB->do_insert( 'lnchapters', array(
				'id'				=> $id,
				'nid'				=> $nid,
				'url'				=> $url,
				'sid'				=> $sid,
				'name'				=> $name,
				'text'				=> $text,
		)		);
		if ($result === false) {
			show_normal_mesR('无法添加当前小说当前本','添加出错','添加');
		}
	}
	
	
	exit;
	
?>